<template>
  <div>
    <!-- <eventStatistics-header
      title="自定义事件"
      @getTime="handleGetTime"
      @getChannel="handleGetChannel"
      @getEvent="handleGetEvent"
    /> -->
    <application-header
      title="自定义事件"
      :backBtnFlag="true"
      @getTime="handleGetTime"
      @getChannel="handleGetChannel"
      @getVersion="handleGetVersion"
    >
      <a-icon slot="backBtn" type="arrow-left" style="font-size: 16px" />
    </application-header>
    <div class="customEventStatistics-container">
      <div class="customEventStatistics-title">
        <!-- <a-icon type="rollback" :style="{color: '#1890ff'}"/> -->
        <span style="color: #000">事件统计：</span>
        <span style="font-size: 14px">{{ eventIdAndEventName }}</span>
      </div>
      <div class="customEventStatistics-tabs">
        <a-tabs default-active-key="1" @change="callback">
          <a-tab-pane key="1" tab="消息数量">
            <div class="chart-wrapper">
              <line-chart
                name="消息数量"
                xAxisName="时间"
                :height="hourHeight"
                :chartData="chartData"
              />
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
      <el-link
        style="margin-left: 16px"
        @click="changePutAwayStatus"
        type="primary"
        :underline="false"
        >{{ putAwayName }}明细数据<i
          :class="[
            isPutAway ? 'el-icon-arrow-up' : 'el-icon-arrow-down',
            'el-icon--right',
          ]"
        ></i
      ></el-link>
      <div class="customEventStatistics-tables">
        <a-table
          v-if="isPutAway"
          :pagination="pagination"
          rowKey="id"
          :columns="columns"
          :data-source="data"
          @change="onChangePagination"
        ></a-table>
      </div>
    </div>
    <div class="customEventStatistics-container">
      <div class="customEventStatistics-title">
        <span style="color: #000">{{ eventIdAndEventName }}参数统计</span>
      </div>
      <el-link
        style="margin-left: 16px"
        @click="changePutAwayStatus2"
        type="primary"
        :underline="false"
        >{{ putAwayName2 }}明细数据<i
          :class="[
            isPutAway2 ? 'el-icon-arrow-up' : 'el-icon-arrow-down',
            'el-icon--right',
          ]"
        ></i
      ></el-link>
      <div class="customEventStatistics-tables">
        <a-table
          v-if="isPutAway2"
          :loading="loading"
          :pagination="pagination2"
          rowKey="id"
          :columns="columns2"
          :data-source="listData"
          @change="onChange"
        >
          <span slot="param" slot-scope="text, record">
            <template>
              <a href="javascript:;" @click="handleGetInfo(record)">{{
                text
              }}</a>
            </template>
          </span>
        </a-table>
      </div>
    </div>
    <a-modal
      title="参数（param）"
      dialogClass="channel-dialog"
      okText=""
      :visible="visible"
      @cancel="handleCancel"
    >
      <template slot="footer">
        <a-button key="submit" type="primary" @click="handleCopy">
          复制
        </a-button>
      </template>
      <div>{{ showParamText }}</div>
    </a-modal>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
// import EventStatisticsHeader from "@/components/EventStatisticsHeader";
import ApplicationHeader from "@/components/ApplicationHeader";
import LineChart from "@/echartsComponent/LineChart.vue";
import {
  getYearMonthDayFromOne,
  getYearMonthDay,
  timestampToTime,
  getFromDay1ToDay2,
} from "@/utils/functions";
import {
  channelSelectListVO,
  getEventDetailList,
} from "@/api/customEventStatistics";

const columns = [
  {
    title: "日期",
    dataIndex: "date",
  },
  {
    title: "消息数量",
    dataIndex: "count",
  },
];

const columns2 = [
  {
    title: "参数值（param）",
    dataIndex: "param",
    scopedSlots: { customRender: "param" },
  },
  {
    title: "时间",
    dataIndex: "createTime", // time
  },
];

function onChangePagination(pagination, filters, sorter) {
  console.log("params", pagination, filters, sorter);
}

export default {
  name: "customEventStatistics",
  data() {
    return {
      showParamText: "",
      visible: false,
      hourHeight: "350px",
      chartData: {
        xAxisData: [],
        yAxisData: [],
      },
      columns,
      columns2,
      data: [],
      listData: [],
      pagination: {
        pageSize: 10,
        total: 0,
      },
      pagination2: {
        pageSize: 10,
        total: 0,
      },
      eventName: "",
      isPutAway: true,
      isPutAway2: true,
      channelSelectListVOData: {
        eventId: "",
        appKey: "",
        startDate: null,
        endDate: null,
        channel: null,
        // event: null,
        version: null,
      },
      queryParam: {
        eventId: "",
        appKey: "",
        startDate: null,
        endDate: null,
        version: null,
        current: 1,
        size: 10,
      },
      loading: false,
    };
  },
  components: {
    // EventStatisticsHeader,
    ApplicationHeader,
    LineChart,
  },
  computed: {
    eventIdAndEventName() {
      return `${this.channelSelectListVOData.eventId}（${this.eventName}）`;
    },
    putAwayName() {
      return this.isPutAway ? "收起" : "展开";
    },
    putAwayName2() {
      return this.isPutAway2 ? "收起" : "展开";
    },
    ...mapGetters(["applicationId"]),
  },
  methods: {
    handleCopy() {
      // 复制文字
      let aux = document.createElement("input");
      aux.setAttribute("value", this.showParamText);
      document.body.appendChild(aux);
      aux.select();
      document.execCommand("copy");
      document.body.removeChild(aux);
      this.$message.success("复制成功！");
    },
    handleCancel(e) {
      this.visible = false;
    },
    handleGetInfo(record) {
      this.visible = true;
      this.showParamText = record.param;
    },
    onChangePagination,
    changePutAwayStatus() {
      this.isPutAway = !this.isPutAway;
    },
    changePutAwayStatus2() {
      this.isPutAway2 = !this.isPutAway2;
    },
    async handleGetTime(msg) {
      this.channelSelectListVOData.startDate = msg[0];
      this.channelSelectListVOData.endDate = msg[1];
      this.queryParam.startDate = msg[0];
      this.queryParam.endDate = msg[1];
      await Promise.all([
        this.getChannelSelectListVO(this.channelSelectListVOData),
        this.getDataFromServer(),
      ]);
    },
    async handleGetChannel(msg) {
      this.channelSelectListVOData.channel = msg.key;
      await this.getChannelSelectListVO(this.channelSelectListVOData);
    },
    // async handleGetEvent(msg) {
    //   this.channelSelectListVOData.event = msg.key;
    //   await this.getChannelSelectListVO(this.channelSelectListVOData);
    // },
    async handleGetVersion(msg) {
      this.channelSelectListVOData.version = msg.key;
      this.queryParam.version = msg.key;
      await Promise.all([
        this.getChannelSelectListVO(this.channelSelectListVOData),
        this.getDataFromServer(),
      ]);
    },
    callback(key) {
      console.log(key);
    },
    formatData(data) {
      const newData = data.map((item) => {
        item.time = timestampToTime(item.time);
        return item;
      });
      return newData;
    },
    async getChannelSelectListVO(data) {
      // 每次请求，清空数据
      this.chartData.xAxisData.length = 0;
      this.chartData.yAxisData.length = 0;
      let res;
      try {
        res = await channelSelectListVO(data);
      } catch (error) {
        console.log(error);
      }
      let { code } = res;
      if (code == 0) {
        let dataM = getFromDay1ToDay2(
          this.channelSelectListVOData.startDate,
          this.channelSelectListVOData.endDate
        );
        // 做些什么
        if (res.data.length == 0) {
          dataM.forEach((item) => {
            this.chartData.xAxisData.push(item);
            this.chartData.yAxisData.push(0);
          });
          this.data = [];
          this.pagination.total = 0;
        } else {
          res.data.forEach((item, index) => {
            item["id"] = index;
          });
          this.data = res.data.reverse();
          for (let i = 0; i < dataM.length; i++) {
            let flag = false;
            let index1;
            for (let j = 0; j < res.data.length; j++) {
              if (res.data[j]["date"] == dataM[i]) {
                flag = true;
                index1 = res.data[j]["count"];
                break;
              }
            }
            if (flag) {
              this.chartData.xAxisData.push(dataM[i]);
              this.chartData.yAxisData.push(index1);
            } else {
              this.chartData.xAxisData.push(dataM[i]);
              this.chartData.yAxisData.push(0);
            }
          }
          this.pagination.total = res.data.length;
        }
      }
    },
    async getDataFromServer() {
      this.loading = true;
      let res;
      try {
        res = await getEventDetailList(this.queryParam);
      } catch (error) {
        this.loading = false;
        console.log(error);
      }
      this.loading = false;
      let { code } = res;
      if (code == 0) {
        // 做些什么
        this.listData = this.formatData(res.data.records);
        this.pagination2.total = res.data.total;
      }
    },
    async onChange(pagination) {
      this.loading = true;
      this.queryParam.current = pagination.current;
      let res;
      try {
        res = await getEventDetailList(this.queryParam);
      } catch (error) {
        this.loading = false;
        console.log(error);
      }
      this.loading = false;
      let { code } = res;
      if (code == 0) {
        // 做些什么
        this.listData = this.formatData(res.data.records);
        this.queryParam.current = res.data.current;
      }
    },
  },
  async mounted() {
    this.channelSelectListVOData.appKey = this.applicationId;
    this.channelSelectListVOData.eventId = this.$route.params.id;
    this.queryParam.appKey = this.applicationId;
    this.queryParam.eventId = this.$route.params.id;
    this.eventName = this.$route.params.name;
    this.channelSelectListVOData.startDate = getYearMonthDayFromOne();
    this.channelSelectListVOData.endDate = getYearMonthDay();
    this.queryParam.startDate = getYearMonthDayFromOne();
    this.queryParam.endDate = getYearMonthDay();
    await Promise.all([
      this.getChannelSelectListVO(this.channelSelectListVOData),
      this.getDataFromServer(),
    ]);
  },
};
</script>

<style lang="scss" scoped>
.customEventStatistics-container {
  margin: 24px 22px 20px;
  padding: 24px;
  background: #fff;
  border-radius: 5px;
  overflow: hidden;
  .customEventStatistics-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 32px;
  }
  .customEventStatistics-tabs {
    position: relative;
    >>> .ant-tabs {
      .ant-tabs-bar {
        border-bottom: none;
        .ant-tabs-nav-container {
          .ant-tabs-nav-wrap {
            .ant-tabs-tab {
              padding: 12px 0;
            }
            .ant-tabs-ink-bar {
              width: 56px;
            }
          }
        }
      }
      .customEventStatistics-tables {
        margin: 24px auto 16px;
      }
    }
    >>> .ant-radio-group {
      position: absolute;
      top: 3px;
      right: 0px;
      padding: 4px 0;
      .ant-radio-button-wrapper {
        margin-right: 8px;
      }
    }
    // chart
    .chart-wrapper {
      background: #fff;
      padding: 16px 0 0;
      margin-bottom: 32px;
    }
  }
  .customEventStatistics-tables {
    margin: 24px auto 16px;
  }
}
</style>

